/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.iasd.youthshelter.datacore.controller;

import pt.iasd.youthshelter.datamodel.service.GraduationSchoolController;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import pt.iasd.youthshelter.datamodel.Pathfinder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import org.openide.util.lookup.ServiceProvider;
import pt.iasd.youthshelter.datacore.EntityManagerSemaphore;
import pt.iasd.youthshelter.datacore.controller.exceptions.NonexistentEntityException;
import pt.iasd.youthshelter.datamodel.GraduationSchool;

/**
 *
 * @author Rui
 */
@ServiceProvider(service=GraduationSchoolController.class)
public class GraduationSchoolJpaController implements Serializable, GraduationSchoolController {

    private EntityManager aquireEntityManager() throws InterruptedException {
        EntityManagerSemaphore.getInstance().getSemaphore().acquire();
        return EntityManagerSemaphore.getInstance().getEntityManager();
    }
    
    private void releaseEntityManager(EntityManager em) {
        if (em != null && em.isOpen()) {
            em.close();
        }
        EntityManagerSemaphore.getInstance().getSemaphore().release();
    }

    @Override
    public void create(GraduationSchool graduationSchool) {
        if (graduationSchool.getPathfinderList() == null) {
            graduationSchool.setPathfinderList(new ArrayList<Pathfinder>());
        }
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            List<Pathfinder> attachedPathfinderList = new ArrayList<Pathfinder>();
            for (Pathfinder pathfinderListPathfinderToAttach : graduationSchool.getPathfinderList()) {
                pathfinderListPathfinderToAttach = em.getReference(pathfinderListPathfinderToAttach.getClass(), pathfinderListPathfinderToAttach.getId());
                attachedPathfinderList.add(pathfinderListPathfinderToAttach);
            }
            graduationSchool.setPathfinderList(attachedPathfinderList);
            em.persist(graduationSchool);
            for (Pathfinder pathfinderListPathfinder : graduationSchool.getPathfinderList()) {
                pathfinderListPathfinder.getGraduationSchoolList().add(graduationSchool);
                pathfinderListPathfinder = em.merge(pathfinderListPathfinder);
            }
            em.getTransaction().commit();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public void edit(GraduationSchool graduationSchool) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            GraduationSchool persistentGraduationSchool = em.find(GraduationSchool.class, graduationSchool.getId());
            List<Pathfinder> pathfinderListOld = persistentGraduationSchool.getPathfinderList();
            List<Pathfinder> pathfinderListNew = graduationSchool.getPathfinderList();
            List<Pathfinder> attachedPathfinderListNew = new ArrayList<Pathfinder>();
            for (Pathfinder pathfinderListNewPathfinderToAttach : pathfinderListNew) {
                pathfinderListNewPathfinderToAttach = em.getReference(pathfinderListNewPathfinderToAttach.getClass(), pathfinderListNewPathfinderToAttach.getId());
                attachedPathfinderListNew.add(pathfinderListNewPathfinderToAttach);
            }
            pathfinderListNew = attachedPathfinderListNew;
            graduationSchool.setPathfinderList(pathfinderListNew);
            graduationSchool = em.merge(graduationSchool);
            for (Pathfinder pathfinderListOldPathfinder : pathfinderListOld) {
                if (!pathfinderListNew.contains(pathfinderListOldPathfinder)) {
                    pathfinderListOldPathfinder.getGraduationSchoolList().remove(graduationSchool);
                    pathfinderListOldPathfinder = em.merge(pathfinderListOldPathfinder);
                }
            }
            for (Pathfinder pathfinderListNewPathfinder : pathfinderListNew) {
                if (!pathfinderListOld.contains(pathfinderListNewPathfinder)) {
                    pathfinderListNewPathfinder.getGraduationSchoolList().add(graduationSchool);
                    pathfinderListNewPathfinder = em.merge(pathfinderListNewPathfinder);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = graduationSchool.getId();
                if (findGraduationSchool(id) == null) {
                    throw new NonexistentEntityException("The graduationSchool with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            GraduationSchool graduationSchool;
            try {
                graduationSchool = em.getReference(GraduationSchool.class, id);
                graduationSchool.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The graduationSchool with id " + id + " no longer exists.", enfe);
            }
            List<Pathfinder> pathfinderList = graduationSchool.getPathfinderList();
            for (Pathfinder pathfinderListPathfinder : pathfinderList) {
                pathfinderListPathfinder.getGraduationSchoolList().remove(graduationSchool);
                pathfinderListPathfinder = em.merge(pathfinderListPathfinder);
            }
            em.remove(graduationSchool);
            em.getTransaction().commit();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public List<GraduationSchool> findGraduationSchoolEntities() {
        return findGraduationSchoolEntities(true, -1, -1);
    }

    @Override
    public List<GraduationSchool> findGraduationSchoolEntities(int maxResults, int firstResult) {
        return findGraduationSchoolEntities(false, maxResults, firstResult);
    }

    private List<GraduationSchool> findGraduationSchoolEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(GraduationSchool.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public List<GraduationSchool> findCurrentGraduationSchoolEntities() {
        return findCurrentGraduationSchoolEntities(true, -1, -1);
    }

    @Override
    public List<GraduationSchool> findCurrentGraduationSchoolEntities(int maxResults, int firstResult) {
        return findCurrentGraduationSchoolEntities(false, maxResults, firstResult);
    }

    private List<GraduationSchool> findCurrentGraduationSchoolEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery cq = cb.createQuery();
            Root<GraduationSchool> root = cq.from(GraduationSchool.class);
            cq.select(root);
            cq.where(cb.greaterThanOrEqualTo(root.get(root.getModel().getSingularAttribute("endDate", Date.class)), cb.currentDate()));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public GraduationSchool findGraduationSchool(Integer id) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            return em.find(GraduationSchool.class, id);
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public int getGraduationSchoolCount() {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<GraduationSchool> rt = cq.from(GraduationSchool.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return 0;
    }
    
}
